﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using RBS.Common;
using RBS.Common.JsonEntity;
using Webdiyer.WebControls.Mvc;

namespace RBS.Admin.Controllers
{
    public class AdvController : BaseController
    {
        //
        // GET: /Adv/ 
        //list
        public ActionResult List(int id = 1, string kword = null)
        {
            const int pageSize = 10;
            ChkAdminLevel("#", RBSEnums.ActionEnum.View.ToString()); //检查权限
            var bll = new RBS.Core.BLL.Sys_Adv();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = strTemp.ToString();
            const string orderby = " id  desc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.Sys_Adv>(dt);
            PagedList<RBS.Core.Model.Sys_Adv> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.Sys_Adv>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.Sys_Adv>();
                arts = new PagedList<RBS.Core.Model.Sys_Adv>(list, id, pageSize, totalItems);
            }
            return View(arts);
        }
        //edit
        public ActionResult Edit(int id = 0)
        {
            var model = new RBS.Core.Model.Sys_Adv{CreateTime = DateTime.Now};
            if (id != 0)
            { 
                var bll = new RBS.Core.BLL.Sys_Adv();
                model = bll.GetModel(id);
            }
            ViewData.Model = model;
            return View();
        }
        [HttpPost]
        public ActionResult Edit(FormCollection collection)
        {

            var a = collection;
            var model = new RBS.Core.Model.Sys_Adv
            {
                AdvName = collection["AdvName"],
                AdvDesc = collection["AdvDesc"],
                AdvLink = collection["AdvLink"],
                AdvImg = collection["AdvImg"],
                AdvStatus = int.Parse(collection["AdvStatus"]),
                AdvPosition = int.Parse(collection["AdvPosition"]),
                CreateTime = DateTime.Now,
                
            };

            var bll = new RBS.Core.BLL.Sys_Adv();
            if (collection["Id"] != "0")
            {
                model.Id = Convert.ToInt32(collection["Id"]);
                bll.Update(model);
                AddAdminLog(RBSEnums.ActionEnum.Edit.ToString(), "修改广告:" + model.Id); //记录日志
            }
            else
            {

                bll.Add(model);
                AddAdminLog(RBSEnums.ActionEnum.Add.ToString(), "添加广告:" + model.Id); //记录日志
            }
            return RedirectToAction("List");
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages();
            ChkAdminLevel("#", RBSEnums.ActionEnum.Delete.ToString()); //检查权限 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    new RBS.Core.BLL.Sys_Adv().Delete(int.Parse(id));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            }
            AddAdminLog(RBSEnums.ActionEnum.Delete.ToString(), "删除"); //记录日志
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("List", "Adv");
            return Json(ret);
        }


        #region 图片上传
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadAdvImg()
        {
            string outpath = "UploadImages" + "\\" + "ADV\\";
            string physicalPath = HttpContext.Server.MapPath("~/") + outpath;
            if (!Directory.Exists(physicalPath))
            {
                Directory.CreateDirectory(physicalPath);
            }
            try
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        var postedFileBase = Request.Files[i];
                        if (postedFileBase != null)
                        {
                            string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + System.IO.Path.GetFileName(postedFileBase.FileName);
                            httpPostedFileBase.SaveAs(physicalPath + filename);
                            outpath += filename;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                outpath = "";
            }
            return Content("../" + outpath);
        }

        #endregion


 

    }
}
